<?php
namespace User\Controller;

use Common\Controller\HomebaseController;
use Think\Cache\Driver\Redis;
use Portal\Model\PostsModel;

class IndexController extends HomebaseController {
    
    // 前台用户首页 (公开)
	public function index() {
	    
		$id=I("get.id",0,'intval');
		
		$users_model=M("Users");
		
		$user=$users_model->where(array("id"=>$id))->find();

		if(empty($user)){
			$this->error("查无此人！");
		}

		$this->assign($user);
		$this->display(":index");

    }
    
    // 前台ajax 判断用户登录状态接口
    function is_login(){
    	if(sp_is_user_login()){
    		$this->ajaxReturn(array("status"=>1,"user"=>sp_get_current_user()));
    	}else{
    		$this->ajaxReturn(array("status"=>0,"info"=>"此用户未登录！"));
    	}
    }

    //退出
    public function logout(){
    	$ucenter_syn=C("UCENTER_ENABLED");
    	if($ucenter_syn){
    		include UC_CLIENT_ROOT."client.php";
    		echo uc_user_synlogout();
    	}
    	session("user",null);//只有前台用户退出
    	redirect(__ROOT__."/");
    }

    public function get_user_id()
    {
        if(sp_is_user_login()){
            $user = sp_get_current_user();
            $this->ajaxReturn(array("status"=>1, "id"=>$user['id']));
        }else{
            $this->ajaxReturn(array("status"=>0, "info"=>"此用户未登录！"));
        }
    }

    // 发送重置密码验证码
    public function send_forget_pwd_key()
    {
        if (IS_POST) {

            $rules = array(
                //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
                array('email', 'require', '邮箱不能为空！', 1 ),
                array('email','email','邮箱格式不正确！',1), // 验证email字段格式是否正确
            );

            $users_model = M("Users");

            if($users_model->validate($rules)->create()===false){
                $this->error($users_model->getError());
            }

            $email      = I('post.email');
            $user_info  = $users_model->where(['user_email' => $email, 'user_status' => 1])->find();

            if ($user_info) {
                $option = M('Options')->where(array('option_name'=>'member_email_active'))->find();
                if(!$option){
                    $this->error('网站未配置账号激活信息，请联系网站管理员');
                }
                $title          = "日新网 -- 重置密码";
                $key            = substr(md5(time().uniqid()), 0, 6);
                $content        = "验证码【" . $key . "】  十分钟内有效，请勿泄露给TA人";


                $redis = Redis::getinstance();
                $redis->set($email . ":auth_code", $key, 60 * 10);


                $send_result = sp_send_email($email, $title, $content);

                if($send_result['error']){
                    $this->error('验证码发送失败，请稍后重试');
                } else {
                    $this->success("验证码已发送至邮箱");
                }
            } else {
                $this->error('邮箱地址错误或用户未激活');
            }
        }
    }

    // 邮箱重置密码
    public function find_password_by_email()
    {
        if (IS_POST) {
            $rules = array(
                //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
                array('email', 'require', '邮箱不能为空！', 1 ),
                array('password','require','密码不能为空！',1),
                array('password','5,20',"密码长度至少5位，最多20位！",1,'length',3),
                array('repassword', 'require', '重复密码不能为空！', 1 ),
                array('repassword','password','确认密码不正确',0,'confirm'),
                array('email','email','邮箱格式不正确！',1), // 验证email字段格式是否正确
            );

            $users_model = M("Users");

            if($users_model->validate($rules)->create()===false){
                $this->error($users_model->getError());
            }

            $email      = I('post.email');
            $password   = I('post.password');
            $auth_code  = I('post.auth_code');

            $user_info  = $users_model->where(['user_email' => $email, 'user_status' => 1])->find();

            if ($user_info) {

                $redis          = Redis::getinstance();
                $_auth_code     = $redis->get($email . ":auth_code");

                if ($auth_code == $_auth_code) {
                    $users_model->where(['id' => $user_info['id']])->save(['user_pass' => sp_password($password)]);
                    $this->success("修改密码成功！", U("user/login/index"));
                } else {
                    $this->error('邮箱验证码错误');
                }
            } else{
                $this->error('邮箱地址错误或用户未激活');
            }
        } else {
            $this->display();
        }
    }


    // 专栏作者个人主页
    public function professor_homepage() {
        $user_id = I('get.professor_id', 0, 'intval');
        if ($user_id) {

            // 用户验证
            $user_info = M('users')->where(['id' => $user_id, 'user_status' => 1])->find();
            if (empty($user_info)) {
                $this->error('无效用户');
                exit;
            }

            // 专栏作者验证
            $professor_info = M('professor')->where(['user_id' => $user_id, 'status' => 1])->find();
            if (empty($professor_info)) {
                $this->error('无效专栏作者');
                exit;
            }

            // 基本信息
            $base_info = array(
                'avatar'                => $user_info['avatar'],
                'user_nicename'         => $user_info['user_nicename'],
                'position'              => $user_info['position'],
                'company'               => $user_info['company'],
                'signature'             => $user_info['signature'],
                'introduction'          => $professor_info['introduction'],
                'fans_qrcode'           => $professor_info['fans_qrcode'] ? sp_get_image_preview_url($professor_info['fans_qrcode']) : '',
                'company_link'          => $user_info['company_link'],
                'company_start_time'    => $user_info['company_start_time'],
                'company_scale'         => $user_info['company_scale'],
                'company_addr'          => $user_info['company_addr'],
                'company_introduction'  => $user_info['company_introduction'],
            );
            if ($base_info['company_scale'] == 0) {
                $base_info['scale'] = "不明确";
            } elseif ($base_info['company_scale'] <= 20 && $base_info['company_scale'] > 0) {
                $base_info['scale'] = "1~20人";
            } elseif ($base_info['company_scale'] <= 100 && $base_info['company_scale'] > 20) {
                $base_info['scale'] = "20~100人";
            } elseif ($base_info['company_scale'] <= 500 && $base_info['company_scale'] > 100) {
                $base_info['scale'] = "100~500人";
            } elseif ($base_info['company_scale'] <= 1000 && $base_info['company_scale'] > 500) {
                $base_info['scale'] = "500~1000人";
            } elseif ($base_info['company_scale'] <= 5000 && $base_info['company_scale'] > 1000) {
                $base_info['scale'] = "1000~5000人";
            } else {
                $base_info['scale'] = "5000人以上";
            }
            $this->assign('base_info', $base_info);

//            $where = ['pf_id' => $professor_info['id'], 'del_time' => 0, 'user_id' => $user_id];
//            // 项目
//            $pf_projects = M('pf_project')->where($where)->select();
//            $this->assign('pf_projects', $pf_projects);
//
//            // 教育
//            $pf_education = M('pf_education')->where($where)->select();
//            $this->assign('pf_education', $pf_education);
//
//            // 出版作品
//            $pf_publish = M('pf_publish')->where($where)->select();
//            $this->assign('pf_publish', $pf_publish);
//
//            // 资格认证
//            $pf_certificate = M('pf_certificate')->where($where)->select();
//            $this->assign('pf_certificate', $pf_certificate);
//
//            // 专利发明
//            $pf_patent = M('pf_patent')->where($where)->select();
//            $this->assign('pf_patent', $pf_patent);
//
//            // 荣誉奖项
//            $pf_award = M('pf_award')->where($where)->select();
//            $this->assign('pf_award', $pf_award);


            $posts_model = M('posts');
            // 专栏文章
            $articles = $posts_model
                ->where(['post_author' => $user_id, 'post_status' => PostsModel::POST_STATUS_NORMAL, 'post_type' => PostsModel::POST_TYPE_ARTICLE])
                ->order('post_order desc, post_hits desc, post_like desc, post_date desc')
                ->field('id, post_title, smeta, post_date')
                ->limit(3)
                ->select();

            foreach ($articles as $k => $v) {
                $smeta = json_decode($v['smeta'], true);
                if (isset($smeta['thumb']) && !empty($smeta['thumb'])) {
                    $v['thumb'] = sp_get_asset_upload_path($smeta['thumb']);
                }
                unset($v['smeta']);
                $articles[$k] = $v;
            }
            $this->assign('articles', $articles);

            // 问答
            // 自己提出的问题
            $question = $posts_model
                ->alias('p')
                ->where(['p.post_author' => $user_id, 'p.post_status' => PostsModel::POST_STATUS_NORMAL, 'p.post_type' => PostsModel::POST_TYPE_DISCUSSION_QUESTION])
                ->order('p.post_order desc, p.post_hits desc, p.post_like desc, p.post_date desc')
                ->field('p.id, p.post_title, p.post_date, (SELECT GROUP_CONCAT(u.avatar) FROM rx_posts p1 LEFT JOIN rx_users u ON u.id = p1.post_author WHERE p1.post_type = ' . PostsModel::POST_TYPE_DISCUSSION_ANSWER . ' and p1.post_status = ' . PostsModel::POST_STATUS_NORMAL . ' and p1.question_id = p.id) as answer_avatars')
                ->limit(3)
                ->select();
            // 自己回答的问题
            $answers = $posts_model
                ->alias('p')
                ->where(['p.post_author' => $user_id, 'p.post_status' => PostsModel::POST_STATUS_NORMAL, 'p.post_type' => PostsModel::POST_TYPE_DISCUSSION_ANSWER])
                ->field('p.question_id')
                ->limit(10)
                ->group('p.question_id')
                ->select();
            if ($answers) {
                $link_questions = $posts_model
                    ->alias('p')
                    ->where(['p.id' => ['in', array_column($answers, 'question_id')], 'p.post_status' => PostsModel::POST_STATUS_NORMAL, 'p.post_type' => PostsModel::POST_TYPE_DISCUSSION_QUESTION])
                    ->order('p.post_order desc, p.post_hits desc, p.post_like desc, p.post_date desc')
                    ->field('p.id, p.post_title, p.post_date, (SELECT GROUP_CONCAT(u.avatar) FROM rx_posts p1 LEFT JOIN rx_users u ON u.id = p1.post_author WHERE p1.post_type = ' . PostsModel::POST_TYPE_DISCUSSION_ANSWER . ' and p1.post_status = ' . PostsModel::POST_STATUS_NORMAL . ' and p1.question_id = p.id) as answer_avatars')
                    ->limit(3)
                    ->select();
                $question = array_merge($question, $link_questions);
            }
            $has_id = array();
            foreach ($question as $k => $v) {
                // 去重
                if (in_array($v['id'], $has_id)) {
                    unset($question[$k]);
                    continue;
                }
                $has_id[] = $v['id'];
                if (empty($v['answer_avatars'])) {
                    $v['answer_avatars'] = [];
                } else {
                    $org_avatars = explode(',', $v['answer_avatars']);
                    $has_avatars = array();
                    foreach ($org_avatars as $v1) {
                        if (!in_array($v, $has_avatars)) {
                            $has_avatars[] = $v1;
                        }
                    }
                    $v['answer_avatars'] = array();
                    foreach ($has_avatars as $v1) {
                        $v['answer_avatars'][] = sp_get_user_avatar_url($v1);
                    }
                    $v['answer_avatars'] = array_slice($v['answer_avatars'], 0, 5);
                }
                $question[$k] = $v;
            }
            $this->assign('question', $question);

            // 接入分享sdk
            if (C('WX_SHARE')) {
                require_once './plugins/wx_jssdk.php';
                $jssdk       = new \JSSDK(C('WX_OFFICIAL_ACCOUNT.APP_ID'), C('WX_OFFICIAL_ACCOUNT.APP_SECRET'));
                $signPackage = $jssdk->GetSignPackage();
                $this->assign('signPackage', $signPackage);
            }

            // 二维码
            require_once './plugins/WxPay/lib/phpqrcode.php';
            $file_name  = "professor_" . $user_id;
            $url        = 'http://' . C('DOMAIN_NAME') . U('User/Index/professor_homepage', ['professor_id' => $user_id]);
            $path       = get_link_qrcode_path($file_name, $url);
            $this->assign('qrcode', $path);

            $this->display();
        } else {
            $this->error('数据有误');
        }
    }

}
